﻿using System.Linq;
using PersonaLibrary.Data;

namespace PersonaLibrary.ViewModel.DepartmentsViewModel
{
    public class DepartmentViewModel : LinqEditableItem<Department, View.DepartmentView.ChangeDepartmentView>
    {
        #region Private members
        
        private readonly Validation.ValidationItem<Organization> _parentOrganization = new Validation.ValidationItem<Organization>();
        
        #endregion

        #region Ctor
        
        public DepartmentViewModel()
        {
            EditableItem = new Department();
            InitValidation();
        }

        public DepartmentViewModel(int id)
        {
            EditableItem = Context.Departments.Single(x => ((Department)x).Id == id);
            InitValidation();
        }

        private void InitValidation()
        {
            _parentOrganization.Source = Context.Organizations;
            _parentOrganization.ValidExpression = x => x.Name.StartsWith(_parentOrganization.ValidationValue);
            _parentOrganization.Selector = x => x.Name;
            if (EditableItem.Organization != null)
            {
                _parentOrganization.ValidationValue = EditableItem.Organization.Name;
                _parentOrganization.ValidateCommand.Execute(null);
                _parentOrganization.MoreThenOneCand = false;
            }
        }

        #endregion
        
        #region Public properties

        public Validation.ValidationItem<Organization> ParentOrganization
        {
            get
            {
                return _parentOrganization;
            }
        }

        #endregion

        #region Parent override
        
        public override void Commit()
        {
            if (!_parentOrganization.IsValid)
            {
                _parentOrganization.ValidateCommand.Execute(null);
                if (!_parentOrganization.IsValid)
                {
                    System.Windows.MessageBox.Show("Ошибка валидации организации, проверьте правильность имени");
                    return;
                }
            }
            else if (string.IsNullOrEmpty(_parentOrganization.ValidationValue))
            {
                System.Windows.MessageBox.Show("Ошибка валидации организации, проверьте правильность имени");
                return;
            }

            EditableItem.OrganizationId =
                    Context.Organizations.Single(x => x.Name == _parentOrganization.ValidationValue).Id;

            base.Commit();
        }

        public override bool CanCommit()
        {
            return _parentOrganization.IsValid;
        }

        #endregion
    }
}
